<template>
  <div id="exescript">
    <div class="myline">
      模板名称：<el-input
        v-model="formData.name"
        :disabled="true"
        style="display: inline"
      ></el-input>
    </div>
    <div class="myline">
      项目名称：<el-input
        v-model="formData.sys"
        :disabled="true"
        style="display: inline; width: 10%"
      ></el-input>
    </div>
    <div class="myline myselect">
      执行环境：
      <el-select
        v-model="formData.env"
        filterable
        placeholder="请选择运行环境"
        style="width: 300px"
      >
        <el-option
          v-for="item in envlist"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          @click.native="choisedb(formData.sys, formData.env)"
        >
        </el-option>
      </el-select>
    </div>
    <div class="myline myselect">
      选数据库：
      <el-select
        v-model="formData.dbconnid"
        filterable
        placeholder="请选择环境对应的库地址"
        style="width: 300px"
      >
        <el-option
          v-for="(item, index) in dbinfoList"
          :key="index"
          :label="item.connname"
          :value="item.id"
          @click.native="getmasterparam(index)"
        >
        </el-option>
      </el-select>
    </div>
    <div class="paramlist">
      <span style="font-weight: 700">分库查询参数:</span>
      <div class="slaveparam" v-show="showslavetips">
        {{ slavetipsinfo }}
      </div>
      <div v-for="(item, key) in formData.slavedbparamlist" :key="key">
        <div class="div1">{{ item.key }}：</div>
        <div class="div2">
          <el-input
            v-model="item.value"
            style="display: inline; width: 10%"
          ></el-input>
        </div>
      </div>
    </div>
    <div class="paramlist">
      <span style="font-weight: 700">模板参数列表:</span>
      <span
        style="font-weight: 400; font-size: 10px; color: red; margin-left: 10px"
        >根据需要执行的条件，编辑相应的参数，如不修改则使用默认参数</span
      >
      <div v-for="(item, key) in formData.paramList" :key="key">
        <div class="div1">{{ item.key }}：</div>
        <div class="div2">
          <el-input
            v-model="item.value"
            style="display: inline; width: 10%"
          ></el-input>
        </div>
      </div>
    </div>
    <div style="clear: both">
      <el-button type="primary" @click="coverscript()">转换脚本</el-button>
      <el-tooltip
        class="item"
        effect="dark"
        content="检查脚本转换是否正确，不正确，可手动修改后提交执行"
        placement="bottom"
      >
        <el-button type="primary" @click="runscript()">执行脚本</el-button>
      </el-tooltip>

      <el-tooltip
        class="item"
        effect="dark"
        content="转换加执行，一起进行"
        placement="bottom"
      >
        <el-button type="danger" @click="submit_exe()">转换加执行</el-button>
      </el-tooltip>
    </div>
    <div class="myline">
      模板转换结果：
      <textarea
        ref="textarea"
        :value="code"
        style="font-family: 微软雅黑"
      ></textarea>
    </div>
    <div class="myline">
      <span style="font-weight: 700">脚本执行结果：</span>
      <div v-for="(item, index) in runResult" :key="index">
        <div class="resulttitle">
          第 {{ item.lineNo }} 行 {{ item.lineData }}行执行结果
        </div>
        <div v-if="item.isError">
          <div class="resutldata">
            <div v-if="item.result[0] || item.result[1].length != 0">
              <el-table
                :data="item.result[1]"
                max-height="250"
                border
                style="width: 100%"
                @cell-dblclick="celldblclick"
                :header-cell-style="{
                  background: '#009ad6',
                  color: '#feeeed',
                  fontweight: '100',
                }"
              >
                <el-table-column
                  label="序号"
                  type="index"
                  align="center"
                  width="50"
                ></el-table-column>
                <el-table-column
                  v-for="(value, key, index) in item.result[1][0]"
                  :key="index"
                  :prop="key"
                  :label="key"
                  :render-header="headerWidthSet"
                >
                  <template slot-scope="scope">
                    <el-popover
                      placement="top-start"
                      width="300"
                      trigger="hover"
                      :disabled="
                        scope.row[scope.column.property].length <=
                        calConetentLength(scope.column.property)
                      "
                    >
                      <div>{{ scope.row[scope.column.property] }}</div>
                      <span
                        slot="reference"
                        v-if="
                          scope.row[scope.column.property].length <=
                          calConetentLength(scope.column.property)
                        "
                        >{{ scope.row[scope.column.property] }}</span
                      >
                      <span
                        slot="reference"
                        v-if="
                          scope.row[scope.column.property].length >
                          calConetentLength(scope.column.property)
                        "
                        >{{
                          scope.row[scope.column.property].substr(
                            0,
                            calConetentLength(scope.column.property)
                          ) + "..."
                        }}</span
                      >
                    </el-popover>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="exefail">
              执行失败:{{ item.result[1][0].errorinfo }}
            </div>
          </div>
        </div>
        <div v-else>
          <div class="errortips">{{ item.mark }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { defineComponent, ref } from "vue";
import axios from "axios";
import _CodeMirror from "codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/idea.css";
import "codemirror/mode/yaml/yaml.js";
import "codemirror/mode/sql/sql.js";
import "codemirror/mode/python/python.js";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/addon/hint/javascript-hint";
import "codemirror/addon/hint/sql-hint";
import "codemirror/addon/hint/anyword-hint";
import common from "@/api/common";

const CodeMirror = window.CodeMirror || _CodeMirror;

export default {
  name: "ExeTemp",
  props: ["rowdata"],
  data() {
    return {
      formData: {
        name: this.rowdata["name"], // 模板名称
        sys: this.rowdata["pjname"], // 项目名称
        pjcode: this.rowdata["pjcode"], // 项目编码
        env: "", // 环境
        dbconnid: "", // 数据库连接配置id
        slavedbparamlist: new Array(), // 分库查询参数列表
        paramList: this.rowdata["paramlist"], //参数列表
      },
      dbinfoList: new Array(),
      code: "执行完自动加载",
      showslavetips: true,
      slavetipsinfo: "选择完环境和库信息之后自动加载分库参数",
      coverflag: false,
      envlist: [
        {
          label: "测试环境",
          value: "QA",
        },
        {
          label: "生产环境",
          value: "PROD",
        },
      ],
      options: {
        tabSize: 2,
        theme: "idea",
        line: true,
        mode: "text/x-sql",
      },
      modes: [
        {
          value: "x-python",
          label: "Python",
        },
        {
          value: "x-sql",
          label: "SQL",
        },
        {
          value: "x-yaml",
          label: "Yaml",
        },
        {
          value: "javascript",
          label: "Json",
        },
      ],
      runResult: new Object(),
      tableColumns: [
        { key: "orgName", name: "办案单位", width: 250 },
        { key: "caseCnt", name: "案件数（件）", minWidth: 120 },
        { key: "remarkCnt", name: "批注（个）", minWidth: 120 },
        { key: "evidenceAuditCnt", name: "添加审查结论（次）", minWidth: 150 },
      ],
    };
  },

  mounted() {
    this._initialize();
  },

  methods: {
    _initialize() {
      this.coder = CodeMirror.fromTextArea(this.$refs.textarea, this.options);
      this.coder.setValue(this.code);
      this.coder.on("change", (coder) => {
        this.code = coder.getValue();
        if (this.$emit) {
          this.$emit("input", this.code);
        }
      });

      if (this.language) {
        let modeObj = this._getLanguage(this.language);
        if (modeObj) {
          this.mode = modeObj.label;
        }
      }
    },

    _getLanguage(language) {
      return this.modes.find((mode) => {
        let currentLanguage = language.toLowerCase();
        let currentLabel = mode.label.toLowerCase();
        let currentValue = mode.value.toLowerCase();
        return (
          currentLabel === currentLanguage || currentValue === currentLanguage
        );
      });
    },

    changeMode(val) {
      this.coder.setOption("mode", `text/${val}`);
      let label = this._getLanguage(val).label.toLowerCase();
      this.$emit("language-change", label);
    },

    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },

    sucessInfo(msg) {
      this.$notify({
        title: "成功",
        message: msg,
        type: "success",
      });
    },

    warningInfo(msg) {
      this.$notify({
        title: "警告",
        message: msg,
        type: "warning",
      });
    },

    coverscript() {
      let request = this.formData;
      request.tpid = this.rowdata["id"];

      if (
        (request.env == null) |
        (request.env == "") |
        (request.dbconnid == null) |
        (request.dbconnid == "")
      ) {
        return this.warningInfo("环境和库为必选项，不能为空");
      }
      const tmpParam = new Object();
      axios({
        method: "post",
        url: "/sqltemplate/conversql",
        Headers: {
          "Content-Type": "application/json",
        },
        withCredentials: true,
        data: request,
      }).then((res) => {
        if (common.checkIsLogin(res)) {
          if (res.data["sucess"] == 1) {
            this.sucessInfo("模板转换成功");
            this.coder.setValue(res.data["data"]);
            this.coverflag = true;
          } else {
            this.warningInfo(res.data["msg"]);
          }
        } else {
          this.errorInfo(res.data.msg);
        }
      });
    },

    getmasterparam(index) {
      this.formData.slavedbparamlist = JSON.parse(
        this.dbinfoList[index].envparamlist
      );
      console.log();
      if (this.formData.slavedbparamlist == 0) {
        this.showslavetips = true;
        this.slavetipsinfo = "当前环境无分库查询参数";
      } else {
        this.showslavetips = false;
      }
    },

    choisedb(pjname, envtype) {
      axios({
        method: "GET",
        url: "/sqltemplate/envinfo?pjname=" + pjname + "&envtype=" + envtype,
        withCredentials: true,
      }).then((res) => {
        if (common.checkIsLogin(res)) {
          if (res.data.code !== 1) {
            this.errorInfo("链接信息获取失败");
          } else {
            this.dbinfoList = res.data.data;
            this.formData.dbconnid = "";
            // this.formData.env = envtype
          }
        } else {
          this.errorInfo(res.data.msg);
        }
      });
    },

    errorInfo(msg) {
      this.$notify.error({
        title: "错误",
        message: msg,
      });
    },

    runscript() {
      if (this.coverflag) {
        const req = new Object();
        req.tpid = this.rowdata.id;
        req.pjname = this.formData.sys;
        req.env = this.formData.env;
        req.dbconnid = this.formData.dbconnid;
        req.slavedbparamlist = this.formData.slavedbparamlist;
        req.script = this.code;
        req.scriptparam = this.formData.paramList;
        axios({
          method: "post",
          url: "/sqltemplate/runscript",
          Headers: {
            "Content-Type": "application/json",
          },
          withCredentials: true,
          data: req,
        }).then((res) => {
          if (common.checkIsLogin(res)) {
            if (res.data["code"] == 1) {
              this.sucessInfo(res.data["msg"]);
              this.runResult = res.data["data"];
            } else {
              this.warningInfo(res.data["msg"]);
            }
          } else {
            this.errorInfo(res.data.msg);
          }
        });
      } else {
        this.warningInfo("请先转换脚本");
      }
    },

    headerWidthSet(h, { column, index }) {
      let labelLong = column.label.length;
      if (labelLong < 10) {
        labelLong = 10;
      }
      let size = 12;
      column.minWidth = labelLong * size;
      return h("span", { class: "cell-content", style: { width: "100%" } }, [
        column.label,
      ]);
    },

    calConetentLength(columnName) {
      if (columnName.length <= 10) {
        length = 20;
      } else if (columnName.length >= 30) {
        length = 60;
      } else {
        length = columnName.length * 2;
      }

      return length;
    },

    celldblclick(row, column, cell, event) {
      this.$copyText(row[column.property]).then(
        (e) => {
          this.$message.success("内容" + row[column.property] + "复制成功");
        },
        (e) => {
          this.$message.success("内容" + row[column.property] + "复制失败");
        }
      );
    },
    cellEvent(event) {
      alert("xxx");
      console.log(event);
    },
  },
};
</script>

<style>
.el-col-3 {
  margin: auto;
}
.el-input .el-input__inner {
  width: 80%;
}
.myline {
  margin-bottom: 15px;
  margin-top: 15px;
  margin-left: 5px;
  font-weight: 700;
  width: 93%;
}

.CodeMirror {
  flex-grow: 1;
  z-index: 1;
  font-size: 20px;
  line-height: 150%;
  height: 300px;
  width: "90%";
  border: 1px solid #5b5b5b;
  margin: 10px;
  border-radius: 3px;
  box-shadow: 5px 5px 5px #888888;
}
.CodeMirror-code {
  line-height: 19px;
}

.code-mode-select {
  position: absolute;
  z-index: 2;
  right: 10px;
  top: 10px;
  max-width: 130px;
  line-height: 19px;
}

.showCode {
  border: 1px solid black;
}

.paramlist {
  border: 1px solid #f0f0f0;
  margin: 10px 10px 10px 3px;
  width: 91%;
  border-radius: 3px;
  box-shadow: 5px 5px 5px #888888;
  background-color: #e0e0e0;
  overflow: hidden;
  padding-bottom: 20px;
  min-height: 100px;
}

.div1 {
  width: 20%;
  float: left;
  text-align: right;
  padding-right: 5px;
  padding-top: 7px;
  top: 50%;
  font-weight: 700;
  font-size: 18px;
}

.div2 {
  width: 78%;
  float: left;
}

.el-button {
  float: none;
  margin-left: 20px;
}

textarea {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 20px;
}

.slaveparam {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
  color: red;
}

.resulttitle {
  color: #33a3dc;
}
.errortips {
  color: red;
  border: 3px solid #a1a3a6;
  box-shadow: 5px 5px 5px #888888;
  background-color: #e0e0e0;
  font-weight: 600;
  margin: 10px 10px 20px 3px;
  font-size: 12px;
}
</style>